#region License
//-----------------------------------------------------------------------------
// Copyright (c) 2008, Aaron MacDougall, Daniel Jeffery
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of Aaron MacDougall or Daniel Jeffery nor the names of its contributors may
//   be used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System.IO;
#endregion

namespace Agro2D
{
    /// <summary>
    /// This class is as a reference to a Texture2D contained in
    /// TextureManager.
    /// </summary>
    public sealed class TextureReference
    {
        #region Fields
        private string fileName;
        #endregion

        #region Properties
        /// <summary>
        /// The file path of the texture.
        /// </summary>
        public string FileName
        {
            get { return this.fileName; }
        }
        #endregion

        #region Constructors/Destructors
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="fileName">The file path of the texture.</param>
        public TextureReference(string fileName)
        {
            Debug.Assert(fileName.Length > 0);
            this.fileName = fileName;
        }
        #endregion
    }

    /// <summary>
    /// A singleton that manages all textures used in the application. Handles
    /// loading of textures, and reloading when a graphics device is reset.
    /// </summary>
    public sealed class TextureManager
    {
        #region Fields
        private static readonly TextureManager instance = new TextureManager();
        private Dictionary<TextureReference, Texture2D> textures;
        private ContentManager content;
        private string contentRootPath;
        private bool inLevelEditor;
        #endregion

        #region Properties
        /// <summary>
        /// Retrieves the singleton instance of this class.
        /// </summary>
        public static TextureManager Instance
        {
            get { return instance; }
        }
        #endregion

        #region Constructors/Destructors
        /// <summary>
        /// Constructor is private because this is a singleton class.
        /// </summary>
        private TextureManager()
        {
            this.textures = new Dictionary<TextureReference, Texture2D>();
        }
        #endregion

        /// <summary>
        /// Must be called from Game.Initialize().
        /// </summary>
        /// <param name="content"></param>
        public void Initialize(ContentManager content, string contentRootPath)
        {
            this.content = content;
            this.contentRootPath = contentRootPath;
        }

        /// <summary>
        /// Must be called from Game.LoadContent() to reload textures when the
        /// graphics device is reset.
        /// </summary>
        public void LoadContent()
        {
            List<TextureReference> references = new List<TextureReference>();

            // Get list of references
            foreach (KeyValuePair<TextureReference, Texture2D> kvp in this.textures)
                references.Add(kvp.Key);

            // Reload all textures
            foreach (TextureReference textureReference in references)
                this.textures[textureReference] = this.content.Load<Texture2D>(textureReference.FileName);
        }

        /// <summary>
        /// Loads a texture and returns a TextureReference object representing
        /// the new texture.
        /// </summary>
        /// <param name="fileName">The file path of the texture.</param>
        /// <returns>Reference to loaded texture.</returns>
        public TextureReference CreateTexture(string fileName)
        {
            TextureReference textureReference = new TextureReference(fileName);

            // Load texture
            Texture2D texture = this.content.Load<Texture2D>(fileName);

            // Add texture along with reference to our collection
            this.textures.Add(textureReference, texture);

            return textureReference;
        }

        /// <summary>
        /// Assumes textures are PNG!
        /// </summary>
        /// <param name="graphicsDevice"></param>
        /// <param name="filename"></param>
        /// <param name="contentRootPath"></param>
        /// <returns></returns>
        public TextureReference CreateEditorTexture(GraphicsDevice graphicsDevice, string filename)
        {
            try
            {
                // If this fails, texture is neither in the same folder as the script or in the content folder
                string filenameExt = contentRootPath + "\\..\\" + filename + ".png";
                return InternalCreateEditorTexture(graphicsDevice, filenameExt);
            }
            catch
            {
            }

            string fullFilename = contentRootPath + "\\" + filename + ".png";
            return InternalCreateEditorTexture(graphicsDevice, fullFilename);           
        }

        private TextureReference InternalCreateEditorTexture(GraphicsDevice graphicsDevice, string filename)
        {
#if WINDOWS
            if(!TextureManager.Instance.ContainsTexture(filename))
            {
                Texture2D texture = Texture2D.FromFile(graphicsDevice, filename);
                TextureReference reference = new TextureReference(filename);
                TextureManager.Instance.AddTextureReference(reference, texture);
                return reference;
            }
            else
            {
                return TextureManager.Instance.GetTextureReference(filename);
            }
#else
            return null;
#endif
        }

        public void AddTextureReference(TextureReference reference, Texture2D texture)
        {
            this.textures.Add(reference, texture);
        }

        /// <summary>
        /// Removes and disposes the texture represented by the specified
        /// TextureReference.
        /// </summary>
        /// <param name="textureReference">Reference to texture.</param>
        public void RemoveTexture(TextureReference textureReference)
        {
            this.textures[textureReference].Dispose();
            this.textures.Remove(textureReference);
        }

        /// <summary>
        /// Clears all textures from the manager. Texture references that are
        /// held onto by other objects will become invalid.
        /// </summary>
        public void Clear()
        {
            foreach (KeyValuePair<TextureReference, Texture2D> kvp in this.textures)
                kvp.Value.Dispose();

            this.textures.Clear();
        }

        /// <summary>
        /// Retrieves the Texture2D object referenced by the specified
        /// TextureReference.
        /// </summary>
        /// <param name="textureReference">Reference to texture.</param>
        /// <returns>Texture2D object used for drawing.</returns>
        public Texture2D GetTexture(TextureReference textureReference)
        {
            Debug.Assert(this.textures.ContainsKey(textureReference));
            return this.textures[textureReference];
        }

        /// <summary>
        /// Instead of creating a new reference, returns a current one
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public TextureReference GetTextureReference(string path)
        {
            foreach(TextureReference reference in this.textures.Keys)
            {
                if(reference.FileName == path)
                    return reference;
            }
            return null;
        }

        /// <summary>
        /// True if texture manager contains a texture matching the passed path
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public bool ContainsTexture(string path)
        {
            foreach(TextureReference reference in this.textures.Keys)
            {
                if(reference.FileName == path)
                    return true;
            }
            return false;
        }


        public bool InLevelEditor
        {
            get { return inLevelEditor; }
            set { inLevelEditor = value; }
        }

    }
}